package com.example.wwk.graduationpractice.Activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.FormatTools;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.R;
import com.example.wwk.graduationpractice.SmackUtils.GetVcardUtils;
import com.example.wwk.graduationpractice.Globalutils.CustomDialogUtils;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.stringencoder.Base64;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;

public class SettingPortraitActivity extends AppCompatActivity {
    //back
    private ImageView back;
    //smack connection
    private AbstractXMPPConnection connection;
    //头像
    private Bitmap globalBitmap;
    private ImageView portrait;
    //button
    private Button chooseAlbum;
    private Button sureImage;
    //加载框
    private CustomDialogUtils progressDialog;
    //case 情况
    private static final int SET_IMAGE_SUCCESS = 1;
    public static final int CHOOSE_PHOTO = 2;
    //handler
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_portrait_activity);
        ActivityCollector.addActivity(this);
        //back
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //intent
        Intent intent = getIntent();
        String userName = intent.getStringExtra("user");
        //获取全局连接
        connection = MyApplication.getConnection();
        //获取openfire服务器内VCard的头像信息
        portrait = (ImageView) findViewById(R.id.setting_portrait);
        Drawable headImage = GetVcardUtils.getUserImage(connection, userName);
        if (headImage != null) {//图片圆形化与压缩大小
            int size = 400;
            Bitmap scaleBitmap = Bitmap.createScaledBitmap(FormatTools.getInstance().drawable2Bitmap(headImage), size, size, true);//压缩图片
            globalBitmap = scaleBitmap;
            portrait.setImageBitmap(scaleBitmap);
        } else {
            portrait.setImageResource(R.drawable.default_header);       //当用户没有自定义头像
        }
        //相册选择
        chooseAlbum = (Button) findViewById(R.id.setting_portrait_choose_button);
        chooseAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(SettingPortraitActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(SettingPortraitActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
            }
        });
        //确认选择图片
        sureImage = (Button) findViewById(R.id.setting_portrait_sure);
        sureImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = new CustomDialogUtils(SettingPortraitActivity.this, R.style.CustomDialog);
                progressDialog.setCancelable(false);        //无法手动取消
                progressDialog.show();
                setVcardImage(globalBitmap);
            }
        });
        //handler
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SET_IMAGE_SUCCESS:
                        PromptShowUtils.showToast("上传成功！");
                        progressDialog.dismiss();
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    /*
    * 设置Vcard头像
    */
    private void setVcardImage(Bitmap bitmap) {
        try {
            setUserImage(connection, FormatTools.getInstance().Bitmap2Bytes(bitmap));
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    /*
    * 设置用户头像
    */
    private void setUserImage(final AbstractXMPPConnection connection,
                              final byte[] image) throws XMPPException {
        final VCard card = new VCard();
        try {
            card.load(connection);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        }
        new Thread() {
            @Override
            public void run() {
                try {
                    AndFilter filter = new AndFilter(new PacketIDFilter(
                            card.getPacketID()), new PacketTypeFilter(IQ.class));
                    //包收集器
                    PacketCollector collector = connection.createPacketCollector(filter);
                    String encodeImage = Base64.encodeToString(image);
                    //设置头像
                    card.setAvatar(image);
                    //设置
                    card.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
                            + encodeImage + "</BINVAL>", true);
                    card.save(connection);
                    IQ iq = (IQ) collector.nextResult(SmackConfiguration
                            .getDefaultPacketReplyTimeout());
//                    if (iq != null && iq.getType() == IQ.Type.result) {//上传成功
                    Message msg = handler.obtainMessage();//省去了创建对象申请内存的开销
                    msg.what = SET_IMAGE_SUCCESS;
                    handler.sendMessage(msg);
//                    }
                } catch (XMPPException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SmackException.NotConnectedException e) {
                    e.printStackTrace();
                } catch (SmackException.NoResponseException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /*
    * 打开相册
    */
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    /*
    * 请求权限结果
    */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    PromptShowUtils.showToast("您拒绝授权！;");
                }
                break;
            default:
        }
    }

    /*
    相册选择照片的返回结果，判断各种系统版本的处理图片方式
    */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    /*
    * 4.4及以上系统使用这个方法处理图片
    */
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    /*
    * 4.4以下系统使用这个方法处理图片
    */
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /*
    * 获得图片路径
    */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /*
    * 展示图片
    */
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            int size = 400;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);//压缩图片
            globalBitmap = scaleBitmap;
            portrait.setImageBitmap(scaleBitmap);
        } else {
            PromptShowUtils.showToast("获取照片失败！");
        }
    }


}
